package com.own.component.common.util;

import com.own.component.common.util.list.ListUtil;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

import java.util.Properties;

/**
 * PropertiesYamlUtil
 *
 * @author chenxueli
 * @date 2023-07-19 15:09:00
 */
public class PropertiesYamlUtil {

    private static final Properties PROPERTIES = new Properties();

    static {
        init();
    }

    public static String get(String key) {
        return PROPERTIES.get(key).toString();
    }

    private static void init() {
        {
            var props = getYmlProperties("application.yml");
            if (props == null) {
                throw new RuntimeException("application.yml not found");
            }
            PROPERTIES.putAll(props);
        }
        {
            var include = PROPERTIES.getProperty("spring.profiles.include");
            if (include != null) {
                ListUtil.Spilt.to(include, ",").forEach(item -> {
                    PROPERTIES.putAll(getYmlProperties("application-" + item + ".yml"));
                });
            }
        }
        // 查询其他配置
        {
            var active = PROPERTIES.getProperty("spring.profiles.active");
            if (active != null) {
                PROPERTIES.putAll(getYmlProperties("application-" + active + ".yml"));
            }
        }
    }

    private static Properties getYmlProperties(String ymlName) {
        var resource = new ClassPathResource(ymlName);
        try {
            var factoryBean = new YamlPropertiesFactoryBean();
            factoryBean.setResources(resource);
            return factoryBean.getObject();
        } catch (Exception e) {
            return null;
        }
    }

}
